#-------------------------------------------------------------------------------
# Name:        zipserver.py
# Purpose:     Use Cherrypy server to view contents of SlideSpeech .zip file
#
# Authors:     John Graves <john.graves@slidespeech.com>
#
# Created:     11 November 2012
# Copyright:   (c) Slidespeech Ltd 2012
# Licence:     MIT license
#-------------------------------------------------------------------------------

import cherrypy
import os
import urllib2
import zipfile

__version__ = "2012-11-11"

# Simple downloading with progress indicator, by Cees Timmerman, 16mar12.

def retrieve(remote,local):

    u = urllib2.urlopen(remote)

    fp = open(local, 'wb')

    blockSize = 8192 #100000 # urllib.urlretrieve uses 8192
    while True:
        chunk = u.read(blockSize)
        if not chunk: break
        fp.write(chunk)

    fp.flush()
    fp.close()
    u.close()

class ServePage():
    def index(self):
        '''Display form for link and version'''
        form = '''<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<html>
<head>
<title></title>
<BODY>
<center>
<form name="myForm" action="viewZip" method="post" enctype="multipart/form-data">
	<table>
		<tbody>
        <tr>
			<td>Link to SlideSpeech:</td><td>Version:</td>
		</tr>

        <tr>
			<td><input type="text" name="link" size="40"></td>
            <td><input type="text" name="version" size="5"></td>
		</tr>

		<tr>
			<td><input type="submit" value="Download ZIP and Open"></td>
		</tr>
	</tbody></table>
</form>
</center>
</BODY>
</HTML>'''

        return form

    index.exposed = True

    def viewZip(self, link, version=None):
        '''Download ZIP file, extract and open it'''
        # Parse link to extract presentation code.
        # For example: ljuPfncten from http://slidespeech.com/s/ljuPfncten/
        linkParts = link.split('/')
        if len(linkParts) > 4:
            code = linkParts[4]
        else:
            code = link

        if version is None or 0==len(version.strip()):
            version = '1'
        else:
            version = version.strip()

        # Prepare URL for downloading.
        # For example: http://slidespeech.com/s/ljuPfncten/slidespeech_ljuPfncten_v1.zip
        url ='http://slidespeech.com/s/'+code+'/slidespeech_'+code+'_v'+version+'.zip'
        outputFile = 'static/slidespeech_'+code+'_v'+version+'.zip'
        try:
            retrieve(url,outputFile)
        except:
            errorMessage = '''<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<html>
<head>
<title></title>
</HEAD>
<BODY>
<center>
<form name="myForm" action="viewZip" method="post" enctype="multipart/form-data">
<table>
<tbody>

<tr>
<td>Link to SlideSpeech:</td>
<td>Version:</td>
</tr>

<tr>
<td><input type="text" name="link" size="40"></td>
<td><input type="text" name="version" size="5"></td>
</tr>

<tr>
<td><input type="submit" value="Download ZIP and Open"></td>
</tr>

<tr>
<td>
Could not download<br>
{0}
<br>to file<br>
{1}
<br>
Check version and try again.</td>
</tr>
</tbody>
</table>
</form>
</center>
</BODY>
</HTML>'''.format(url,outputFile)
            return errorMessage

        # Open .zip file and return redirect to index.html
        zf = zipfile.ZipFile(outputFile,'r')
        zf.extractall('static')
        redirect = '''<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<html>
<head>
<title></title>
<meta http-equiv="REFRESH" content="0;url=static/slidespeech_{0}_v{1}/index.html"></HEAD>
<BODY>
</BODY>
</HTML>'''.format(code,version)
        return redirect

    viewZip.exposed = True

if __name__ == '__main__':
    # CherryPy always starts with app.root when trying to map request URIs
    # to objects, so we need to mount a request handler root. A request
    # to '/' will be mapped to HelloWorld().index().
    cherrypy.config.update({'server.socket_host': '127.0.0.1',
                        'server.socket_port': 10080,
                        'server.thread_pool': 10,
                       })
    config = {'/': {'tools.staticdir.root': os.path.abspath(os.curdir)},
              '/static':{'tools.staticdir.on':True,
                         'tools.staticdir.dir':"static"}}
    cherrypy.quickstart(ServePage(), config=config)
